package com.lyhengtongwl.zqsnews.manage;

import android.media.MediaPlayer;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.widget.CustomRotateAnim;

public class MyMediaManager {
    private MediaPlayer mMediaPlayer;  // 手机媒体播放器对象
    private static MyMediaManager instance = new MyMediaManager();

    private MyMediaManager() {
    }

    public static MyMediaManager getInstance() {
        return instance;
    }

    public void playAudio(int ringID, ImageView imageView) {
        if (mMediaPlayer != null) {
            stopAudio();//停止铃声播放
        }
        try {
            CustomRotateAnim rotateAnim = CustomRotateAnim.getCustomRotateAnim();
            // 一次动画执行1秒
            rotateAnim.setDuration(500);
            // 设置为循环播放
            rotateAnim.setRepeatCount(-1);
            // 设置为匀速
            rotateAnim.setInterpolator(new LinearInterpolator());
            // 开始播放动画
            imageView.startAnimation(rotateAnim);
            //下面是调用振动的三行代码/之后调用的是铃声
            mMediaPlayer = MediaPlayer.create(App.getContext(), ringID);
            mMediaPlayer.setLooping(false);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    imageView.clearAnimation();
                    imageView.setImageResource(R.drawable.red_unnormal);
                }
            });
            mMediaPlayer.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 铃声关闭
     */
    private void stopAudio() {
        // 此处必须要进行判空！！！
        if (mMediaPlayer != null) {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();//暂停
            }
            mMediaPlayer.release();//释放掉资源
            mMediaPlayer = null;
        }
    }
}
